package com.powernode.customer.service.impl;

import com.powernode.common.constant.RedisConstant;
import com.powernode.common.execption.PowerException;
import com.powernode.common.result.Result;
import com.powernode.customer.client.CustomerInfoFeignClient;
import com.powernode.customer.service.CustomerService;
import com.powernode.model.form.customer.UpdateWxPhoneForm;
import com.powernode.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private CustomerInfoFeignClient customerInfoFeignClient;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * <p>小程序登录</p>
     * <p>1. 讲小程序发送的code传入下游服务</p>
     * <p>2. 根据下游服务返回的用户id结合token放入redis</p>
     * <p>3. 返回token给前端小程序</p>
     */
    @Override
    public String login(String code) {
        Result<Long> result = customerInfoFeignClient.login(code);
        if (result.getCode() != 200)
            throw new PowerException(result.getCode(), result.getMessage());
        Long customerId = result.getData();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token,
                customerId.toString(), RedisConstant.USER_LOGIN_REFRESH_KEY_TIMEOUT, TimeUnit.SECONDS);
        return token;
    }

    /**
     * 获取用户登录信息
     */
    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        Result<CustomerLoginVo> result = customerInfoFeignClient.getCustomerLoginInfo(customerId);
        return result.getData();
    }

    /**
     * 更新手机号码
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        Result<Boolean> result = customerInfoFeignClient.updateWxPhoneNumber(updateWxPhoneForm);
        return result.getData();
    }
}